<template>
  <div class="employee-manage-view">
    <!-- 搜索栏 -->
    <el-form :inline="true" :model="searchForm" class="search-bar">
      <el-form-item>
        <el-input v-model="searchForm.keyword" placeholder="请输入账号/昵称搜索" clearable prefix-icon="el-icon-search" />
      </el-form-item>
      <el-form-item>
        <el-input v-model="searchForm.company" placeholder="所属企业" clearable style="width: 160px" />
      </el-form-item>
      <el-form-item>
        <el-input v-model="searchForm.role" placeholder="角色" clearable style="width: 120px" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 工具栏 -->
    <div class="toolbar">
      <el-button type="primary" icon="el-icon-plus" @click="handleAdd">新增</el-button>
      <el-button>导入</el-button>
      <el-button>导出</el-button>
      <el-button @click="handleBatchDelete">批量删除</el-button>
    </div>

    <!-- 表格 -->
    <el-table :data="tableData" border stripe style="width: 100%" class="employee-table" @selection-change="handleSelectionChange" :scrollbar-always-on="true">
      <el-table-column type="selection" width="48" />
      <el-table-column prop="account" label="账号" width="120" />
      <el-table-column prop="companyId" label="所属企业" width="160" />
      <el-table-column prop="phone" label="手机号" width="140" />
      <el-table-column prop="email" label="邮箱" width="180" />
      <el-table-column prop="roleId" label="角色" width="120" />
      <el-table-column prop="creator" label="创建人" width="100" />
      <el-table-column prop="createTime" label="创建时间" width="180" />
      <el-table-column prop="status" label="状态" width="90" fixed="right">
        <template #default="scope">
          <el-switch v-model="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180" fixed="right">
        <template #default="scope">
          <el-button type="text" @click="editRow(scope.row, scope.$index)">编辑</el-button>
          <el-button type="text" @click="resetPwd(scope.row)">重置密码</el-button>
          <el-button type="text" style="color: #ff4d4f" @click="deleteRow(scope.row, scope.$index)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-bar">
      <span>共 {{ total }} 条</span>
      <el-pagination
        v-model:current-page="page.current"
        v-model:page-size="page.size"
        :page-sizes="[10, 20, 50]"
        :total="total"
        layout="sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
      />
    </div>

    <el-dialog :title="dialogTitle" v-model="dialogVisible">
      <el-form :model="form" label-width="80px">
        <el-form-item label="账号">
          <el-input v-model="form.account" />
        </el-form-item>
        <el-form-item label="所属企业">
          <el-input v-model="form.companyId" />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="form.phone" />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="form.email" />
        </el-form-item>
        <el-form-item label="角色">
          <el-input v-model="form.roleId" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleDialogConfirm">確定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { dataAPI } from '../../http/leancloud'

/**
 * 此页面对应企业管理下的员工管理
 */


const searchForm = ref({ keyword: '', company: '', role: '' })
const companyOptions = ref<any[]>([])
const roleOptions = ref<any[]>([])
const tableData = ref<any[]>([])
const total = ref(0)
const page = ref({ current: 1, size: 10 })
const dialogVisible = ref(false)
const dialogTitle = ref('新增员工')
const form = ref<any>({
  employeeId: '',
  nickname: '',
  account: '',
  companyId: '',
  phone: '',
  email: '',
  roleId: '',
  creator: '管理员',
  status: true
})
const editIndex = ref(-1)
const multipleSelection = ref<any[]>([])

function formatDate(date: Date) {
  const y = date.getFullYear()
  const m = String(date.getMonth() + 1).padStart(2, '0')
  const d = String(date.getDate()).padStart(2, '0')
  const h = String(date.getHours()).padStart(2, '0')
  const min = String(date.getMinutes()).padStart(2, '0')
  const s = String(date.getSeconds()).padStart(2, '0')
  return `${y}-${m}-${d} ${h}:${min}:${s}`
}

const fetchCompanies = async () => {
  const results = await dataAPI.query('Company')
  companyOptions.value = results.map((item: any) => ({ label: item.name, value: item.objectId }))
}
const fetchRoles = async () => {
  const results = await dataAPI.query('Role')
  roleOptions.value = results.map((item: any) => ({ label: item.name, value: item.objectId }))
}
const fetchEmployees = async () => {
  const where: any = {}
  if (searchForm.value.keyword) {
    where.account = { "$regex": searchForm.value.keyword }
  }
  if (searchForm.value.company) {
    where.companyId = {
      "__type": "Pointer",
      "className": "Company",
      "objectId": searchForm.value.company
    }
  }
  if (searchForm.value.role) {
    where.roleId = {
      "__type": "Pointer",
      "className": "Role",
      "objectId": searchForm.value.role
    }
  }
  const results = await dataAPI.query('Employee', where)
  total.value = results.length
  tableData.value = results.map((item: any) => {
    // companyId、roleId直接显示原始值
    return {
      objectId: item.objectId,
      employeeId: item.employeeId,
      nickname: item.nickname,
      account: item.account,
      companyId: typeof item.companyId === 'string' ? item.companyId : item.companyId?.objectId || '',
      phone: item.phone,
      email: item.email,
      roleId: typeof item.roleId === 'string' ? item.roleId : item.roleId?.objectId || '',
      creator: item.creator,
      status: item.status === 1,
      createTime: item.createdAt ? formatDate(new Date(item.createdAt)) : ''
    }
  })
}

const handleSearch = () => {
  fetchEmployees()
}
const handleReset = () => {
  searchForm.value = { keyword: '', company: '', role: '' }
  fetchEmployees()
}
const handleSelectionChange = (val: any[]) => {
  multipleSelection.value = val
}
const handleSizeChange = (size: number) => {
  page.value.size = size
  fetchEmployees()
}
const handlePageChange = (current: number) => {
  page.value.current = current
  fetchEmployees()
}
const handleAdd = () => {
  dialogTitle.value = '新增员工'
  form.value = {
    employeeId: '',
    nickname: '',
    account: '',
    companyId: '',
    phone: '',
    email: '',
    roleId: '',
    creator: '管理员',
    status: true
  }
  editIndex.value = -1
  dialogVisible.value = true
}
const editRow = (row: any, index: number) => {
  dialogTitle.value = '编辑员工'
  form.value = {
    objectId: row.objectId,
    employeeId: row.employeeId,
    nickname: row.nickname,
    account: row.account,
    companyId: row.companyId,
    phone: row.phone,
    email: row.email,
    roleId: row.roleId,
    creator: row.creator,
    status: row.status
  }
  editIndex.value = index
  dialogVisible.value = true
}
const resetPwd = (row: any) => {}
const handleDialogConfirm = async () => {
  const data = {
    employeeId: form.value.employeeId,
    nickname: form.value.nickname,
    account: form.value.account,
    companyId: {
      "__type": "Pointer",
      "className": "Company",
      "objectId": form.value.companyId
    },
    phone: form.value.phone,
    email: form.value.email,
    roleId: {
      "__type": "Pointer",
      "className": "Role",
      "objectId": form.value.roleId
    },
    creator: form.value.creator,
    status: form.value.status ? 1 : 0
  }
  if (editIndex.value === -1) {
    await dataAPI.save('Employee', data)
    ElMessage.success('新增成功')
  } else {
    await dataAPI.save('Employee', { ...data, objectId: form.value.objectId })
    ElMessage.success('修改成功')
  }
  dialogVisible.value = false
  fetchEmployees()
}
const deleteRow = (row: any, index: number) => {
  ElMessageBox.confirm(
    `确认刪除账号 "${row.account}" 吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    await dataAPI.delete('Employee', row.objectId)
    ElMessage.success('刪除成功')
    fetchEmployees()
  }).catch(() => {})
}
const handleBatchDelete = () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning('请先选择要刪除的员工！')
    return
  }
  ElMessageBox.confirm(
    `确认刪除选中的 ${multipleSelection.value.length} 个员工吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    for (const item of multipleSelection.value) {
      await dataAPI.delete('Employee', item.objectId)
    }
    ElMessage.success('刪除成功')
    fetchEmployees()
    multipleSelection.value = []
  }).catch(() => {})
}

onMounted(() => {
  fetchCompanies()
  fetchRoles()
  fetchEmployees()
})
</script>

<style scoped>
.employee-manage-view {
  padding: 16px 12px 0 12px;
  background: #f7f9fb;
  min-height: 100vh;
}
.search-bar {
  background: #fff;
  padding: 12px 16px 8px 16px;
  border-radius: 6px;
  margin-bottom: 10px;
  display: flex;
  align-items: center;
}
.search-bar .el-form-item {
  margin-right: 12px;
  margin-bottom: 0;
}
.toolbar {
  background: #fff;
  padding: 10px 16px 10px 16px;
  border-radius: 6px;
  margin-bottom: 10px;
  display: flex;
  align-items: center;
}
.toolbar .el-button {
  margin-right: 8px;
}
.employee-table {
  background: #fff;
  border-radius: 6px;
  margin-bottom: 16px;
  /* 横向滚动 */
  overflow-x: auto;
}
.employee-table .el-table__header th {
  background: #f7f9fb;
  color: #333;
  font-weight: 500;
}
.employee-table .el-button[type="text"] {
  padding: 0 6px;
  font-size: 14px;
}
.employee-table .el-button[type="text"]:not(:last-child) {
  margin-right: 4px;
}
.employee-table .el-button[type="text"]:nth-child(3) {
  color: #ff4d4f;
}
.pagination-bar {
  background: #fff;
  border-radius: 6px;
  padding: 10px 16px;
  display: flex;
  align-items: center;
  gap: 16px;
}
.pagination-bar .el-pagination {
  margin-left: 8px;
}
</style> 